/*
 *
 *  *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  *  <p>
 *  *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  *  you may not use this file except in compliance with the License.
 *  *  You may obtain a copy of the License at
 *  *  <p>
 *  * https://www.gnu.org/licenses/lgpl.html
 *  *  <p>
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package com.base.pig.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.base.pig.constant.CacheConstants;
import com.base.pig.dto.DictTree;
import com.base.pig.entity.SysDict;
import com.base.pig.entity.SysDictItem;
import com.base.pig.util.R;
import com.base.pig.service.SysDictService;
import com.base.pig.service.SysDictItemService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2019-03-19
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/dict")
@Api(value = "dict", tags = "字典管理")
public class DictController {
	private final SysDictItemService sysDictItemService;
	private final SysDictService sysDictService;

	/**
	 * 通过ID查询字典信息
	 *
	 * @param id ID
	 * @return 字典信息
	 */
	//@SysLog("通过ID查询字典信息")
	@GetMapping("/{id}")
	public R getById(@PathVariable Long id) {
		return R.ok(sysDictService.getById(id),"查询信息成功");
	}

	/**
	 * @Title getList 根据类型返回dto
	 * @Description
	 * @return com.pig4cloud.pig.common.core.util.R
	 * @author zhangzhy
	 * @date 2020/4/23 17:31
	 */
	//@SysLog("通过类型返回字典项list")
	@GetMapping("/list/{type}")
	public R getList(@PathVariable String type){
		if(StrUtil.isNotBlank(type)){
			List<SysDictItem> dictItemsList = sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getType,type));
			if(dictItemsList != null){
				List<DictTree> dictDtosList = dictItemsList.stream().map(sysDictItem -> {
					DictTree dictDto = new DictTree();
					dictDto.setLabel(sysDictItem.getLabel());
					dictDto.setType(sysDictItem.getType());
					dictDto.setValue(sysDictItem.getValue());
					return dictDto;
				}).collect(Collectors.toList());
				return R.ok(dictDtosList,"查询成功");
			}
			return R.failed(null,"未查询到该类型信息");
		}
		return R.failed(null,"参数异常");
	}
	/**
	 * 分页查询字典信息
	 *
	 * @param map 条件查询
	 * @return 分页对象
	 */
	@PostMapping("/page")
	public R getDictPage(@RequestBody Map map) {
		return sysDictService.getDictPage(map);
	}

	/**
	 * 通过字典类型查找字典
	 *
	 * @param type 类型
	 * @return 同类型字典
	 */
	//@SysLog("通过字典类型查找字典")
	@GetMapping("/type/{type}")
	@Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type")
	public R getDictByType(@PathVariable String type) {
		return R.ok(sysDictItemService.list(Wrappers
				.<SysDictItem>lambdaQuery()
				.eq(SysDictItem::getType, type).orderByAsc(SysDictItem::getSort)));
	}

	/**
	 * 添加字典
	 *
	 * @param sysDict 字典信息
	 * @return success、false
	 */
	//@SysLog("添加字典")
	@PostMapping
	public R save(@Valid @RequestBody SysDict sysDict) {
		sysDict.setDelFlag("0");
		sysDict.setCreateTime(LocalDateTime.now());
		sysDict.setType(sysDict.getType().toLowerCase());
		long i = sysDictService.count(Wrappers.<SysDict>query().lambda().eq(SysDict::getType,sysDict.getType()));
		if(i!=0){
			return R.failed("当前类型编码已存在");
		}
		boolean b = sysDictService.save(sysDict);
		if(b){
			return R.ok(b,"添加成功");
		}
		return R.failed(b,"添加失败");
	}

	/**
	 * 删除字典，并且清除字典缓存
	 *
	 * @param id ID
	 * @return R
	 */
	//@SysLog("删除字典")
	@GetMapping("/delete/{id}")
	public R removeById(@PathVariable Long id) {
		return sysDictService.removeDict(id);
	}

	/**
	 * 修改字典
	 *
	 * @param sysDict 字典信息
	 * @return success/false
	 */
	@PostMapping("/edit")
	//@SysLog("修改字典")
	public R updateById(@Valid @RequestBody SysDict sysDict) {
		if(sysDict.getId()!=null){
            long count = sysDictService.count(Wrappers.<SysDict>query().lambda().eq(SysDict::getId,sysDict.getId()));
			if(count != 0){
				return sysDictService.updateDict(sysDict);
			}
			return R.failed(null,"未找到该数据");
		}
		return R.failed(null,"ID数据错误");
	}

	/**
	 * 分页查询
	 *
	 * @param map        分页参数
	 * @return
	 */
	//@SysLog("分页查询字典项")
	@PostMapping("/item/page")
	public R getSysDictItemPage(@RequestBody Map map) {
		return sysDictItemService.getSysDictItemPage(map);
	}

	/**
	 * 通过id查询字典项
	 *
	 * @param id id
	 * @return R
	 */
	//@SysLog("通过id查询字典项")
	@GetMapping("/item/{id}")
	public R getDictItemById(@PathVariable("id") Long id) {
        long count = sysDictItemService.count(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getId, id));
		if (count !=  0){
			return R.ok(sysDictItemService.getById(id),"查询成功");
		}
		return R.failed(null,"未找到数据");
	}

	/**
	 * 新增字典项
	 *
	 * @param sysDictItem 字典项
	 * @return R
	 */
	//@SysLog("新增字典项")
	@PostMapping("/item")
	@CachePut(value = CacheConstants.DICT_DETAILS ,key = "#sysDictItem.type")
	public R save(@RequestBody SysDictItem sysDictItem) {
		SysDict sysDict = sysDictService.getById(sysDictItem.getDictId());
		if(sysDict != null){
			sysDictItem.setDelFlag("0");
			sysDictItem.setCreateTime(LocalDateTime.now());
            long count = sysDictItemService.count(Wrappers.<SysDictItem>query().eq("value",sysDictItem.getValue()).eq("type",sysDictItem.getType()));
			if(count == 0){
				boolean b = sysDictItemService.save(sysDictItem);
				if (b){
					return R.ok(b,"添加成功");
				}
				return R.failed(null,"添加失败");
			}
			return R.failed(null,"当前数据值已存在");
		}
		return R.failed(null,"当前字典信息不存在");
	}

	/**
	 * 修改字典项
	 *
	 * @param sysDictItem 字典项
	 * @return R
	 */
	//@SysLog("修改字典项")
	@PostMapping("/item/edit")
	public R updateById(@RequestBody SysDictItem sysDictItem) {
        long count = sysDictService.count(Wrappers.<SysDict>query().lambda().eq(SysDict::getId,sysDictItem.getDictId()));
		if(count != 0){
			return sysDictItemService.updateDictItem(sysDictItem);
		}
		return R.failed(null,"当前字典不存在");
	}

	/**
	 * 通过id删除字典项
	 *
	 * @param id id
	 * @return R
	 */
	//@SysLog("通过id删除字典项")
	@GetMapping("/item/delete/{id}")
	public R removeDictItemById(@PathVariable Long id) {
		return sysDictItemService.removeDictItem(id);
	}

}
